package com.weakteam.orderonline.adminconsole.web;


import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;
import com.weakteam.orderonline.adminconsole.bean.ImageStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;


/**
 * @author Nail
 */
@Controller
public class ImageNetService {

    private static final Logger log = LoggerFactory.getLogger(ImageNetService.class);

    @Autowired
    ImageStore imageStore;

    private void initJSONHeader(final HttpServletResponse httpResponse){
        httpResponse.setHeader("Connection", "close");
        httpResponse.setHeader("Content-Type", "application/json");
        httpResponse.setHeader("Expires", "Thu, 19 Nov 1981 08:52:00 GMT");
        httpResponse.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
        httpResponse.setHeader("Pragma", "no-cache");
        httpResponse.setCharacterEncoding("UTF-8");
    }

    @RequestMapping(value = "/getImage")
    public void getImage(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) {
        try {
            String mobile = httpRequest.getParameter("mobile");
            boolean forMobile = false;
            if (mobile != null && mobile.equalsIgnoreCase("true")) forMobile = true;

            String name = httpRequest.getParameter("name");

            File imageFile = imageStore.getImageFile(name, forMobile);
            if (imageFile != null) {
                if (name.endsWith(".png")) {
                    httpResponse.setHeader("Content-Type", "image/png");
                } else if (name.endsWith(".jpg")) {
                    httpResponse.setHeader("Content-Type", "image/jpg");
                }
                httpResponse.setHeader("Content-Length", Long.toString(imageFile.length()));

                FileInputStream in = new FileInputStream(imageFile);
                OutputStream out = httpResponse.getOutputStream();

                // Copy the contents of the file to the output stream
                byte[] buf = new byte[1024];
                int count = 0;
                while ((count = in.read(buf)) >= 0) {
                    out.write(buf, 0, count);
                }
                out.close();
                in.close();
            } else {
                this.initJSONHeader(httpResponse);
                PrintWriter out = httpResponse.getWriter();
                out.print("file not found");
                out.flush();
                out.close();
            }

        } catch (IOException ex) {
            log.error("getImage {}", ex);
        }
    }

    @RequestMapping(value = "/uploadImage")
    public void uploadImage(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) {
        ServletInputStream inputStream = null;
        try {
            String name = httpRequest.getParameter("name");
            inputStream = httpRequest.getInputStream();
            String fileName = this.imageStore.saveImageFile(inputStream, name);

            this.initJSONHeader(httpResponse);
            PrintWriter out = httpResponse.getWriter();
            out.print(fileName);
        } catch (IOException ex) {
            log.error("uploadImages {}", ex);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ex) {
                    log.error("uploadImages close stream {}", ex);
                }
            }
        }
    }

    @RequestMapping(value = "/deleteUnnecessaryImageFiles")
    public void deleteUnnecessaryImageFiles(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) {
        ServletInputStream inputStream = null;
        try {
            this.initJSONHeader(httpResponse);
            PrintWriter out = httpResponse.getWriter();
            this.imageStore.deleteUnnecessaryFiles();
            out.print("deleted");
        } catch (IOException ex) {
            log.error("deleteUnnecessaryImageFiles {}", ex);
        }
    }

    @RequestMapping(value = "/getQRCodeImage")
    public void getQRCodeImage(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) {
        try {
            String qrtext = httpRequest.getParameter("qrText");

            ByteArrayOutputStream outStream = QRCode.from(qrtext).to(ImageType.PNG).stream();

            httpResponse.setContentType("image/png");
            httpResponse.setContentLength(outStream.size());

            OutputStream out = httpResponse.getOutputStream();

            out.write(outStream.toByteArray());
            out.flush();
            out.close();

        } catch (IOException ex) {
            log.error("getQRCodeImage {}", ex);
        }
    }

}
